<?php

function mytheme_raw_login_form()
{
	if(!is_user_logged_in()){
		return mytheme_raw_login_fields();
	}else{
		wp_redirect(home_url());
		exit;
	}

}

add_shortcode("raw_login_form","mytheme_raw_login_form");

function mytheme_raw_login_fields()
{
	ob_start();
	?>
	<div class="alert">
		<?php echo wp_cache_get("login_error_username");?>
	</div>
	<form action="" method="post">
		<div class="mb-3">
			<label for="username">Username or Email</label>
			<input type="text" name="username" id="username">
		</div>
		<div class="mb-3">
			<label for="password">Password</label>
			<input type="password" name="password" id="password">
		</div>
		<button type="submit" class="btn btn-primary" name="login_submit">Submit</button>
	</form>
<?php
	return ob_get_clean();
}

function mytheme_process_login_form()
{
	if(isset($_POST["login_submit"])){
		if(empty($_POST["username"])){
			return wp_cache_add("login_error","username field cannot be empty");
		}

		if(empty($_POST["password"])){
			return wp_cache_add("login_error","username field cannot be empty");
		}

		$login_arg = array(
		   'user_login' => 	$_POST["username"],
		   'user_password' => $_POST["password"],
		   'remember' => true
		);

		$user = wp_signon($login_arg);

		if(is_wp_error($user)){
	        return wp_cache_add("login_error", $user->get_error_messages());
		}else{
			wp_redirect(home_url());
			exit;
		}
	}
}